package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/hashicorp/go-uuid"
	"os"
	"perfect-vue-admin/global"
	"perfect-vue-admin/global/response"
	"perfect-vue-admin/model"
	"perfect-vue-admin/model/request"
	resp "perfect-vue-admin/model/response"
	"perfect-vue-admin/service"
	"perfect-vue-admin/utils"
	"strconv"
	"strings"
)

func UploadImage(c *gin.Context) {
	image_file, err := c.FormFile("image")
	if err != nil {
		response.FailWithMessage("图片上传失败", c)
		global.LOG.Error(err.Error())
		return
	}
	uid, _ := uuid.GenerateUUID()
	filepath := "static/upload/image/" + uid + ".png"
	if err := c.SaveUploadedFile(image_file, filepath); err != nil {
		response.FailWithMessage("图片保存失败", c)
	}else{
		image_url := "/"+ filepath
		response.OkWithData(gin.H{"msg": nil, "name": uid, "url": image_url}, c)
	}
	return
}

//func DeleteFile(c *gin.Context) {
//	var file request.File
//	err := c.ShouldBindJSON(&file)
//	if err != nil {
//		response.FailWithMessage("参数获取失败", c)
//		return
//	}
//	err = os.Remove(file.FilePath)
//	if err != nil {
//		response.FailWithMessage(err.Error(), c)
//	}else{
//		response.OkWithMessage("删除成功", c)
//	}
//	return
//}

func UploadExcel(c *gin.Context) {
	var excel_data request.ExcelData
	err := c.ShouldBindJSON(&excel_data)
	if err != nil {
		response.FailWithMessage("接收数据有误", c)
		return
	}
	fmt.Println(excel_data)
	response.Ok(c)
	return
}


func GetFileList(c *gin.Context) {
	var queryInfo request.PageInfo
	if err := c.ShouldBind(&queryInfo); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	files, total, err := service.GetFileList(queryInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
	} else {
		response.OkWithData(resp.PageResult{
			List:     files,
			Total:    total,
			Page:     queryInfo.Page,
			PageSize: queryInfo.PageSize,
		}, c)
	}
	return
}

func UploadFile(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	file_type_list := strings.Split(file.Filename, ".")
	var file_type string
	if len(file_type_list) > 0 {
		file_type = file_type_list[len(file_type_list)-1]
	}else {
		file_type = ""
	}
	uid, _ := uuid.GenerateUUID()
	filepath := "static/upload/file/" + uid + "." + file_type
	if err := c.SaveUploadedFile(file, filepath); err != nil{
		response.FailWithMessage(err.Error(), c)
	}else{
		var size string
		if file.Size > 1000 {
			size = strconv.FormatInt(file.Size / 1000, 10) + "KB"
		}else {
			size = strconv.FormatInt(file.Size, 10) + "B"
		}
		global.DB.Create(&model.SysFile{Path:"/"+ filepath,Name:file.Filename,Size:size, Type:file_type})
		response.OkWithData("/"+filepath, c)
	}
	return
}

func FileDownload(c *gin.Context)  {
	var file model.SysFile
	_ = c.ShouldBindJSON(&file)
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", file.Name +"." + file.Type))//fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
	c.Writer.Header().Add("Content-Type", "application/octet-stream")
	c.File(strings.Trim(file.Path, "/"))
}

func DeleteFile(c *gin.Context) {
	var file model.SysFile
	err := c.ShouldBindJSON(&file)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
	}
	file_path := strings.Trim(file.Path, "/")
	if err := os.Remove(file_path); err != nil {
		response.FailWithMessage(err.Error(), c)
	}else{
		global.DB.Unscoped().Delete(&file)
		response.OkWithMessage("删除成功", c)
	}
	return
}

func UpdateFileName(c *gin.Context)  {
	var file request.FileRename
	if err := c.ShouldBindJSON(&file); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := service.FileRename(file); err != nil{
		response.FailWithMessage(err.Error(), c)
	}else {
		response.OkWithMessage("重命名成功", c)
	}
	return

}


// @Tags ExaFileUploadAndDownload
// @Summary 上传文件示例
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce  application/json
// @Param file formData file true "上传文件示例"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"上传成功"}"
// @Router /fileUploadAndDownload/upload [post]
func Upload(c *gin.Context) {
	noSave := c.DefaultQuery("noSave", "0")
	_, header, err := c.Request.FormFile("file")
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("上传文件失败，%v", err), c)
	} else {
		// 文件上传后拿到文件路径
		var uploadErr error
		var filePath string
		var key string
		if global.CONFIG.System.OssType == "local" {
			// 本地上传
			uploadErr, filePath, key = utils.UploadFileLocal(header)
		} else {
			// 七牛云上传
			uploadErr, filePath, key = utils.UploadRemote(header)
		}
		if uploadErr != nil {
			response.FailWithMessage(fmt.Sprintf("接收返回值失败，%v", err), c)
		} else {
			// 修改数据库后得到修改后的user并且返回供前端使用
			var file model.ExaFileUploadAndDownload
			file.Url = filePath
			file.Name = header.Filename
			s := strings.Split(file.Name, ".")
			file.Tag = s[len(s)-1]
			file.Key = key
			if noSave == "0" {
				err = service.Upload(file)
			}
			if err != nil {
				response.FailWithMessage(fmt.Sprintf("修改数据库链接失败，%v", err), c)
			} else {
				response.OkDetailed(resp.ExaFileResponse{File: file}, "上传成功", c)
			}
		}
	}
}

// @Tags ExaFileUploadAndDownload
// @Summary 删除文件
// @Security ApiKeyAuth
// @Produce  application/json
// @Param data body model.ExaFileUploadAndDownload true "传入文件里面id即可"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"返回成功"}"
// @Router /fileUploadAndDownload/deleteUploadFile [post]
func DeleteUploadFile(c *gin.Context) {
	var file model.ExaFileUploadAndDownload
	_ = c.ShouldBindJSON(&file)
	err, f := service.FindFile(file.ID)
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("删除失败，%v", err), c)
	} else {
		err = utils.DeleteFile(f.Key)
		if err != nil {
			response.FailWithMessage(fmt.Sprintf("删除失败，%v", err), c)

		} else {
			err = service.DeleteFile(f)
			if err != nil {
				response.FailWithMessage(fmt.Sprintf("删除失败，%v", err), c)
			} else {
				response.OkWithMessage("删除成功", c)
			}
		}
	}
}

// @Tags ExaFileUploadAndDownload
// @Summary 分页文件列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.PageInfo true "分页获取文件户列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /fileUploadAndDownload/getUploadFileList [post]
func GetUploadFileList(c *gin.Context) {
	var pageInfo request.PageInfo
	_ = c.ShouldBindJSON(&pageInfo)
	err, list, total := service.GetFileRecordInfoList(pageInfo)
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("获取数据失败，%v", err), c)
	} else {
		response.OkWithData(resp.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, c)
	}
}
